package com.bp.hearthealth.pulse.lnapps.bp_view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.Scroller
import android.widget.TextView


class BPScrollableTextView : TextView {
    private var mScroller: Scroller? = null
    private var mLastY = 0f
    private var mTouchSlop = 0

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        init(context)
    }

    private fun init(context: Context) {
        mScroller = Scroller(context)
        mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val y = event.y
        when (event.action) {
            MotionEvent.ACTION_DOWN -> mLastY = y
            MotionEvent.ACTION_MOVE -> {
                val deltaY = y - mLastY
                if (Math.abs(deltaY) > mTouchSlop) {
                    scrollBy(0, -deltaY.toInt())
                }
                mLastY = y
            }

            MotionEvent.ACTION_UP -> {}
        }
        return true
    }

    override fun computeScroll() {
        if (mScroller!!.computeScrollOffset()) {
            scrollTo(mScroller!!.currX, mScroller!!.currY)
            postInvalidate()
        }
    }

    fun smoothScrollTo(destX: Int, destY: Int) {
        val scrollX = scrollX
        val scrollY = scrollY
        val deltaX = destX - scrollX
        val deltaY = destY - scrollY
        mScroller!!.startScroll(scrollX, scrollY, deltaX, deltaY, 1000)
        invalidate()
    }
}



